# -*- coding: utf-8 -*-
import cgi
import datetime
import math
import wsgiref.handlers

from google.appengine.ext import db
import enhancedModel as em
import models.option as om
from models.enhancedModel import EnhancedModel as EM

class CityModel ( em.EnhancedModel ):
  name  = db.StringProperty ()
  code = db.StringProperty ()
  position = db.GeoPtProperty()
  positionText = db.StringProperty()
  
  __prefix__ = 'City'
  
  def showLink (self):
    return ("/cities/show1/id/%d" % self.ident)
    
  def showAllLink (self):
    return ("/cities/showAll")
    
  def editLink (self):
    return ("/cities/edit/id/%d" % self.ident)
    
  def newLink (self):
    return ("/cities/new")
    
  def deleteLink (self):
    return ("/cities/delete/id/%d" % self.ident)


  @staticmethod
  def calculateDistance(pos1, pos2):
    start_long = math.radians(pos1.lon)
    start_latt = math.radians(pos1.lat)
    end_long = math.radians(pos2.lon)
    end_latt = math.radians(pos2.lat)
    d_latt = end_latt - start_latt
    d_long = end_long - start_long
    a = math.sin(d_latt/2)**2 + math.cos(start_latt) * math.cos(end_latt) * math.sin(d_long/2)**2
    c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
    return 6371 * c
    
  @staticmethod
  def positionFromCode(code):
    return CityModel.queryLatest(CityModel).filter('code =', code).get().position
  
  @staticmethod      
  def nearestCityCode(pos):
    maxDistance = int(EM.queryLatest(om.OptionModel).filter('name =', "sameCityRadius").get().value)
    cities = CityModel.queryLatest(CityModel).fetch(1000)
    cities.sort(key = lambda c : CityModel.calculateDistance(c.position, pos))
    if CityModel.calculateDistance(cities[0].position, pos)<maxDistance:
      return cities[0].code
    return None